package com.jxb.seven;

/**
 * 示例 1：
 * 输入：nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
 * 输出：3
 * 解释：长度最长的公共子数组是 [3,2,1]
 *
 * dp[i][j]表示最长公共子数组的个数
 * (nums1[i-1] = nums2[j-1]条件下：
 * 状态转移公式：dp[i][j] = dp[i-1][j-1] + 1
 *
 */
public class MaxRepeatedSubarray_718 {


    //标准的dp数组实现
    public int findLength(int[] nums1, int[] nums2) {
        int n1l = nums1.length;
        int n2l = nums2.length;

        int[][] dp = new int[n1l+1][n2l+1];
        int result = 0;
        for (int i = 1;i<=n1l;i++) {
            for (int j = 1;j<=n2l;j++) {
                if (nums1[i-1] == nums2[j-1]) {
                    dp[i][j] = dp[i-1][j-1] + 1;
                }
                result = Math.max(result,dp[i][j]);
            }
        }
        return result;
    }

    //一维滚动数组实现
    // * 输入：nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
    // * 输出：3
    // i = 3,遍历num2
    //int[] dp = [1,2,3,0,0,0]
    public int findLength2(int[] nums1, int[] nums2) {
        int n1l = nums1.length;
        int n2l = nums2.length;

        int[] dp = new int[n2l + 1];
        int result = 0;
        for (int i = 1;i<=n1l;i++) {
            for (int j = n2l;j > 0;j--) {
                if (nums1[i-1] == nums2[j-1]) {
                    dp[j] = dp[j-1] + 1;
                }else {
                    dp[j] = 0;
                }
                result = Math.max(result,dp[j]);
            }
        }
        return result;
    }



}
